package com.muzi.onvif.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class OnvifUtils {

    public static String sendMessage( String url, String soapXml) {
        // 添加请求头
        String headers = "text/xml; charset=utf-8";

        try {
            URL endpoint = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", headers);
            connection.setDoOutput(true);

            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(soapXml.getBytes());
            outputStream.flush();

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                System.out.println("SOAP Success Response:");
                System.out.println(response.toString());
                connection.disconnect();
                return response.toString();

            } else {

                System.out.println("Error sending SOAP request. Response Code: " + responseCode);
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                // 打印响应的XML
                System.out.println("SOAP Error Response:");
                System.out.println(response.toString());
                connection.disconnect();
               return response.toString();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


}
